package com.xxg.renrensearch.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxg.renrencommon.domain.bean.CarryProductInfo;
import com.xxg.renrencommon.domain.bean.ProductGatherInfo;
import com.xxg.renrencommon.domain.filedenum.productenum.ProductOptEnum;
import com.xxg.renrensearch.dao.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据库操作接口
 *
 * @author xuxiaogang
 * @date 2021-12-16
 */
@Service
public class DbService {
    private final Logger logger = LoggerFactory.getLogger(DbService.class);
    private final RenrenShopGoodsDao renrenShopGoodsDao;
    private final RenrenShopGoodsOptionDao renrenShopGoodsOptionDao;
    private final RenrenShopGoodsCategoryMapDao renrenShopGoodsCategoryMapDao;
    private final RenrenShopGoodsSpecDao renrenShopGoodsSpecDao;
    private final RenrenShopGoodsSpecItemDao renrenShopGoodsSpecItemDao;
    private final CarryProductInfoDao carryProductInfoDao;
    private final ProductGatherInfoDao productGatherInfoDao;

    public DbService(RenrenShopGoodsDao renrenShopGoodsDao, RenrenShopGoodsOptionDao renrenShopGoodsOptionDao,
                     RenrenShopGoodsCategoryMapDao renrenShopGoodsCategoryMapDao,
                     RenrenShopGoodsSpecDao renrenShopGoodsSpecDao,
                     RenrenShopGoodsSpecItemDao renrenShopGoodsSpecItemDao, CarryProductInfoDao carryProductInfoDao,
                     ProductGatherInfoDao productGatherInfoDao) {
        this.renrenShopGoodsDao = renrenShopGoodsDao;
        this.renrenShopGoodsOptionDao = renrenShopGoodsOptionDao;
        this.renrenShopGoodsCategoryMapDao = renrenShopGoodsCategoryMapDao;
        this.renrenShopGoodsSpecDao = renrenShopGoodsSpecDao;
        this.renrenShopGoodsSpecItemDao = renrenShopGoodsSpecItemDao;
        this.carryProductInfoDao = carryProductInfoDao;
        this.productGatherInfoDao = productGatherInfoDao;
    }

    /**
     * 根据商品ID删除商品数据
     *
     * @param spuIds 商品ID列表
     */
    @Async("dbExecutor")
    public void deleteData(List<Integer> spuIds) {
        logger.info("用户删除的商品ID为:" + spuIds.toString());
        // 从mongodb中查询带货记录
        List<CarryProductInfo> infos = carryProductInfoDao.findCarryInfosBySpuIds(spuIds);
        // 从mongodb中删除原始被带货商品信息
        carryProductInfoDao.deleteBySpuIds(spuIds);
        List<Integer> ids = infos.stream().map(CarryProductInfo::getCarrySpuId).collect(Collectors.toList());
        logger.info("查询带货记录后，需要删除的带货商品ID为:" + ids.toString());
        if (ids.size() == 0) {
            return;
        }
        renrenShopGoodsDao.deleteByIds(ids);
        renrenShopGoodsOptionDao.deleteByIds(ids);
        renrenShopGoodsCategoryMapDao.deleteByIds(ids);
        renrenShopGoodsSpecDao.deleteByIds(ids);
        renrenShopGoodsSpecItemDao.deleteByIds(ids);
        logger.info("带货的商品等信息删除结束");
    }

    /**
     * 检查带货或采集的商品日志，查漏补缺
     *
     * @param carryGatherLog 带货或采集的商品日志
     */
    @Async("dbExecutor")
    public void checkNewProductCarryInfo(Map<Integer, String> carryGatherLog) {
        logger.info("检查带货和采集日志开始");
        carryGatherLog.forEach((integer, s) -> {
            try {
                JSONObject jsonObject = JSON.parseObject(s);
                Integer opType = jsonObject.getInteger("optFlag");
                if (ProductOptEnum.CARRY.getFlag().equals(opType)) {
                    // 带货处理，检查带货记录是否存在，不存在则补全
                    CarryProductInfo info = jsonObject.getObject("optInfo", CarryProductInfo.class);
                    if (!carryProductInfoDao.existCarryInfo(info.getCarrySpuId())) {
                        carryProductInfoDao.insert(info);
                        logger.info("补充带货记录,carrySpuId:" + info.getCarrySpuId());
                    }
                } else if (ProductOptEnum.GATHER.getFlag().equals(opType)) {
                    // 采集处理，检查采集记录是否存在，不存在则补全
                    ProductGatherInfo info = jsonObject.getObject("optInfo", ProductGatherInfo.class);
                    if (!productGatherInfoDao.existGatherIinfo(info.getNewSpuId())) {
                        productGatherInfoDao.insert(info);
                        logger.info("补充采集记录,newSpuId:" + info.getNewSpuId());
                    }
                } else {
                    logger.info("非带货和采集日志信息:" + s);
                }
            } catch (Exception e) {
                logger.error("检查带货和采集日志异常", e);
            }
        });
        logger.info("检查带货和采集日志结束");
    }
}
